<?php
namespace app\index\controller;

use app\common\model\UserWallet as UserWalletModel;
use app\common\model\Seed as SeedModel;

class Shop extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

    public function index() {
    	$userId = \think\Session::get('user_id');

		$this -> view -> assign('userWallet', UserWalletModel::get(['user_id' => $userId]));

        return $this -> view -> fetch();
    }

	public function handleBuyFirst() {
		$post = $this -> request -> post();
		$FRUIT_FIRST_LIMIT_EACH_PRICE = getFarmParam('FRUIT_FIRST_LIMIT_EACH_PRICE');
		$price = $FRUIT_FIRST_LIMIT_EACH_PRICE * $post['num'];

		return $this -> handleBuy('first', $price);
	}

	public function handleBuySecond() {
		$post = $this -> request -> post();
		$FRUIT_SECOND_LIMIT_EACH_PRICE = getFarmParam('FRUIT_SECOND_LIMIT_EACH_PRICE');
		$price = $FRUIT_SECOND_LIMIT_EACH_PRICE * $post['num'];

		return $this -> handleBuy('second', $price);
	}

	private function handleBuy($type, $price) {
		$userId = \think\Session::get('user_id');
		$currentTime = time();

		$userWalletModelGet = UserWalletModel::get(['user_id' => $userId]);
		if($price > $userWalletModelGet -> gold) {
			return ['code' => -1, 'message' => '您的金币不足！'];
		}

		\think\Db::startTrans();
		try {
			$userWalletModelGet -> gold -= $price;
			if(!$userWalletModelGet -> save()) {
				throw new \Exception('购买失败, UserWalletModel save!');
			}

			if(!SeedModel::where('user_id', $userId) -> setInc('seed_' . $type, $price)) {
				throw new \Exception('购买成功, seed setInc!');
			}

			$seedLogClass = '\\app\\common\\component\\seed\\Seed' . ucfirst($type) . 'LogService';
			$seedLogCreate = (new $seedLogClass()) -> create([
				'user_id' => $userId,
				'type' => 1,
				'active' => 1,
				'price' => $price,
				'create_time' => $currentTime,
				'remark' => '购买种子'
			]);
			if($seedLogCreate['code'] != 0) {
				throw new \Exception($seedLogCreate['message']);
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			return ['code' => -1, 'message' => $e -> getMessage()];
		}
		return ['code' => 0, 'message' => '购买成功'];
	}
}
?>